$.fn.extend({
    defaultText: function(){
        var alt = $(this).attr("alt"), txt = $(this).val();
        $.each(this, function(){
            $(this).focus(function(){
                $(this).val("");
            });
            $(this).blur(function(){
                if (txt == "" || txt == alt) 
                    $(this).val(alt);
            });
        });
    },
    unbind_: function(){
        $(this).each(function(){
            $(this).unbind('dragStart');
            $(this).unbind('dragEnd');
            $(this).unbind('draging');
        });
    }
});

function string2Object(string){
    eval("var result = " + (string));
    return result;
}

function string2Array(string){
    eval("var result = " + (string));
    return result;
}

function min(obj){
    var min = obj[0];
    var len = obj.length;
    for (var i = 1; i < len; i++) {
        if (obj[i] < min) {
            min = obj[i];
        }
    }
    return min;
}

function max(obj){
    var max = obj[0];
    var len = obj.length;
    for (var i = 1; i < len; i++) {
        if (obj[i] > max) {
            max = obj[i];
        }
    }
    return max;
}

$.fn.survay = function(options, setting){
    return this.each(function(){
        Survey(this, options, setting);
    });
}

function Survey(element, options, setting){
    return this instanceof Survey ? this.init(element, options, setting) : new Survey(element, options, setting);
}

$.extend(Survey, {
    form_description: "#form_description",
    form_title: "#form_title",
    widget_container: "#widget-container",
    setting: {
        save_btn: "#save",
        panel: ".form-widget-div",
        form_widget: "<div class='form-widget-container' style='height: auto;'></div>",
        widget: {
            widget_entry: {
                q_class: ".form-widget-entry",
                q_title: ".q_title",
                q_help: ".q_help",
                q_short: ".q_short"
            },
            tool_bar: {
                id: ".fw_tb",
                edit: ".edit",
                clone: ".clone",
                remove: ".remove"
            },
            widget_div: {
                id_end: ".fw_e",
                header: {
                    id: {//e.g entry_id.fw_title
                        title_end: ".fw_title",
                        help_end: ".fw_ht",
                        type_end: ".fw_select",
                        goto_page: ".fw_gtpf",
                        goto_page_box: ".fw_gtpcb"
                    }
                },
                button: {//e.g entry_id.fw_done
                    id: {
                        done_end: ".fw_done",
                        req_end: ".fw_req"
                    }
                },
                preview: {
                    id_end: ".fw_entry",//e.g entry_id.fw_entry
                    name: {//e.g entry.single.entry_id
                        single_pre: "entry.single.",
                        group_pre: "entry.group."
                    },
                    group_id: {//single widget  no id e.g group_:entry_id.position
                        id_pre: "group_:"
                    }
                }
            }
        
        }
    },
    options: {},
    entry: {
        text: {
            label: '文本',
            value: 1
        },
        textarea: {
            label: '段落',
            value: 2
        },
        radios: {
            label: '单选',
            value: 3
        },
        checkboxs: {
            label: '多选',
            value: 4
        },
        select: {
            label: '列表',
            value: 5
        }
    },
    entry_preview: function(init_num){
        return ['empty', "<div><input type='text' name='undefined' disabled='true' class='widget-disabled-preview' value='Their answer'></div>", '<div><input type="text" class="widget-disabled-preview" name="undefined" disabled="true" value="Their longer answer" style="height: 7em; width: 35em;"></div>', '<div><ul class="widget-group-ul"><li><input type="radio" class="" name="item_group:' + init_num + '">' +
        '<input type="text" dir="ltr" style="text-align: left;" value="option" class="">img:http://<input value="" class="img_url">or<input type="button" value="上传" class="upload_btn"></li>' +
        '<li>' +
        '<input type="radio" disabled="true" name=""><input type="text" class="widget-ghost-input" value="click to add option">' +
        '<span class="sv_inline_block">' +
        '<label class="add_other_option">' +
        'or <a href="#">add "Other"</a>' +
        '</label>' +
        '</span>' +
        '</li>' +
        '</ul>' +
        '</div>', '<div><ul class="widget-group-ul"><li><input type="checkbox" class="" name="item_group:' + init_num + '">' +
        '<input type="text" dir="ltr" style="text-align: left;" value="option" class="">图片:http://<input value="" class="img_url">or<input type="button" value="上传" class="upload_btn"></li>' +
        '<li>' +
        '<input type="checkbox" disabled="true" name=""><input type="text" class="widget-ghost-input" value="click to add option">' +
        '<span class="sv_inline_block">' +
        '<label class="add_other_option">' +
        'or <a href="#">add "Other"</a>' +
        '</label>' +
        '</span>' +
        '</li>' +
        '</ul>' +
        '</div>', '<ol class="widget-group-ol">' +
        '<li>' +
        '<input type="text" mark="select" dir="ltr" style="text-align: left;" value="option" class="">' +
        '</li>' +
        '<li><input type="text" value="click to add option" class="widget-ghost-input">' +
        '</li>' +
        '</ol>']
    },
    q_title: "<span class='q_title'></span>",
    q_require: "<span class='q_require'>*</span>",
    q_help: "<span class='q_help'></span>",
    form_widget_entry: function(num){
        return '<div dir="ltr" style="text-align: left;" entryId=' + num + ' class="form-widget-entry"></div>';
    },
    item_delete_button: "<span class='item_delete_button' style='margin:auto 5px;cursor:default'>x</span>",
    get_widget_div: function(num){
        var widget = Survey.setting.widget;
        var entry = Survey.entry;
        var init_num = typeof num == "number" ? num : Survey.get_init_num();
        var widget_div = "<div class='form-widget-div' id=':" + init_num + widget.widget_div.id_end + "'>" +
        "<div class='widget-header'><table><tbody><tr><th class='ss-header'>" +
        "<span>问题</span>" +
        "</th><td>" +
        "<input id=':" +
        init_num +
        widget.widget_div.header.id.title_end +
        "' style='text-align: left;'value='Sample Question' dir='ltr'>" +
        "</td></tr><tr><th class='ss-header'><span>问题补充</span></th><td>" +
        "<input id=':" +
        init_num +
        widget.widget_div.header.id.help_end +
        "' style='text-align: left;'></td></tr><tr>" +
        "<th class='ss-header'><span>控件选项</span></th><td>" +
        "<select id=':" +
        init_num +
        widget.widget_div.header.id.type_end +
        "'>" +
        "<option selected='true' value='" +
        entry.text.value +
        "'>" +
        entry.text.label +
        "</option>" +
        "<option value='" +
        entry.textarea.value +
        "'>" +
        entry.textarea.label +
        "</option>" +
        "<option value='" +
        entry.radios.value +
        "'>" +
        entry.radios.label +
        "</option>" +
        "<option value='" +
        entry.checkboxs.value +
        "'>" +
        entry.checkboxs.label +
        "</option>" +
        "<option value='" +
        entry.select.value +
        "'>" +
        entry.select.label +
        "</option>" +
        "</select>" +
        "<span id=':" +
        init_num +
        widget.widget_div.header.id.goto_page +
        "' style='display:none;'>" +
        "<input type='checkbox' style='width:auto' id=':" +
        init_num +
        widget.widget_div.header.id.goto_page_box +
        "'> " +
        "<label for=':" +
        init_num +
        widget.widget_div.header.id.goto_page_box +
        "'>跳题</label>" +
        "</span>" +
        "</td></tr></tbody>" +
        "</table></div>" +
        "<div class='widget-preview' id=':" +
        init_num +
        widget.widget_div.preview.id_end +
        "'>" +
        "<div><input type='text' value='Their answer' disabled='true' class='widget-disabled-preview' name='undefined'>" +
        "</div></div>" +
        "<div class='widget-button'><button id=':" +
        init_num +
        widget.widget_div.button.id.done_end +
        "'>Done</button>" +
        "&nbsp;&nbsp;<input type='checkbox' id=':" +
        init_num +
        widget.widget_div.button.id.req_end +
        "'>" +
        "<label for=':" +
        init_num +
        widget.widget_div.button.id.req_end +
        "'> &nbsp;必填项</label></div></div>";
        
        var widget_tool_bar = "<div style='border: 1px dashed ;' id=':" + init_num + widget.tool_bar.id + "' class='tool-bar'>" +
        "<a id=':" +
        init_num +
        widget.tool_bar.edit +
        "'  href='#' class='edit'>编辑</a>" +
        "<a id=':" +
        init_num +
        widget.tool_bar.clone +
        "'  href='#' class='clone'>添加</a>" +
        "<a id=':" +
        init_num +
        widget.tool_bar.remove +
        "'  href='#' class='remove'>删除</a>" +
        "</div>";
        
        return widget_tool_bar + widget_div;
    },
    other_option_check: function(num){
        return '<li><input type="checkbox" mark="other" name="item_group:' + num + '"> 其他: <input type="text" class="widget-disabled-preview" disabled="" value="Their own answer"><span class="item_delete_button_other" style="margin:auto 5px;cursor:default">x</span></li>'
    },
    other_option_radio: function(num){
        return '<li><input type="radio" mark="other" name="item_group:' + num + '"> 其他: <input type="text" class="widget-disabled-preview" disabled="" value="Their own answer"><span class="item_delete_button_other" style="margin:auto 5px;cursor:default">x</span></li>'
    },
    init_num: 0,
    get_init_num: function(){
        return ++Survey.init_num;
    }
    
});

$.extend(Survey.prototype, {
    init: function(element, options, setting){
        var self = this;
        this.setting = $.extend(Survey.setting, setting || {});
        this.options = $.extend(Survey.options, options || {});
        this.removeOption = [];
        this.changeVal = 1;
        this.widget = Survey.setting.widget;
        this.entry = Survey.entry;
        this.selectChangeEvent();
        this.addOption();
        this.addOtherOption();
        this.convertToEntry();
        this.addForm(this.options);
        this.clone();
        this.remove();
        this.editEntry();
        $("#form_title").bind('blur', function(e){
            var title = $(this).val();
            self.setFormTitle(title);
        });
        $("#form_description").bind('blur', function(e){
            var des = $(this).val();
            self.setFormDes(des);
        });
        this.save_all(this.setting.saveUrl);
        $(".form-widget-container").hover(function(){
            $(this).find('.form-widget-entry').css({
                'background': '#FFF9DD'
            });
            $(this).find(".tool-bar").css("visibility", 'visible');
        }, function(){
            $(this).find('.form-widget-entry').css({
                'background': '#FFFFFF'
            });
            $(this).find(".tool-bar").css("visibility", 'hidden');
        });
        $("[entrytype=3]").each(function(){
            var id = $(this).attr("entryid");
            self.jumpQuesEvent(id);
        });
    },
    selectChangeEvent: function(){
        var self = this;
        $("[id$='fw_select']").live('change', function(){
            var attr = $(this).attr('id'), val = $(this).val();
            var en_num = parseInt(attr.substring(1, attr.indexOf('.')));
            $("[id=':" + en_num + self.widget.widget_div.preview.id_end + "']").empty().append(Survey.entry_preview(en_num)[val]);
            self.jumpQuesEvent(en_num);
            if (val == 3) {
                $("[id=':" + en_num + ".fw_gtpf']").css('display', '');
            }
            else {
                $("[id=':" + en_num + ".fw_gtpf']").css('display', 'none');
                $("[id=':" + en_num + ".fw_gtpcb']").removeAttr("checked");
            }
        });
    },
    jumpQuesEvent: function(entry_id){
        var self = this;
        $("[id=':" + entry_id + ".fw_gtpcb']").unbind('click').bind('click', function(){
            if ($(this).is(":checked")) {
                var attr = $(this).attr('id');
                var en_num = parseInt(attr.substring(1, attr.indexOf('.')));
                var selectQues = self.getGtpSelect(en_num);
                $(this).parents(".form-widget-div").eq(0).find('[id$="fw_entry"] [name*="item_group"]').parent('li').append(selectQues);
            }
            else {
                $('select[class=:' + entry_id + '.fw_gp]').remove();
            }
            
        });
    },
    getGtpSelect: function(entry_id, selectedPageNum){
        $entry = this.getEntryById(entry_id);
        //position 是从0开始的
        $pos = $entry.Position;
        $leng = this.options.Entries.length;
        var selectQues = "<select class=':" + entry_id + ".fw_gp'><option value='0'>请选择跳转题号</option>";
        for (var i = $pos + 2; i <= $leng; i++) {
            if (i == selectedPageNum) {
                selectQues = selectQues + "<option value='" + i + "' selected=true>第" + i + "题</option>";
            }
            else {
                selectQues = selectQues + "<option value='" + i + "'>第" + i + "题</option>";
            }
        }
        selectQues += "</select>";
        return selectQues;
    },
    setChangeStatus: function($flag){
        this.changeStatus = $flag;
    },
    getChangeStatus: function(){
        return this.changeStatus;
    },
    changeStatus: false,
    addForm: function(option){
        var self = this;
        var FormTitle = option.FormTitle;
        var FormDescription = option.FormDescription;
        var FormId = option.FormId;
        var FormKey = option.FormKey;
        var Entries = option.Entries;
        var entry_num = $(option.Entries).length;
        
        $("#form_title").val(FormTitle);
        $("#form_description").val(FormDescription);
        
        if (entry_num == 0) {
            this.addFormWidget();
        }
        else {
            this.addEntries(Entries);
        }
        $("[id*='.fw_done']").trigger("click");
        
    },
    addEntries: function(entires){
        var self = this;
        Survey.init_num = max(this.getEntryIds());
        $.each(entires, function(index, item){
            var typeId = this.EntryType;
            var EntryId = this.EntryId;
            var QuestionTitle = this.QuestionTitle;
            var HelpText = this.HelpText;
            var EntryType = this.EntryType;
            var Required = this.Required;
            var Position = this.Position;
            var Choices = this.Choices;
            var is_Goto = this.is_Goto;
            self.addFormWidget(function($data){
                $this = $data;
                /**问题\问题补充\问题类型设置**/
                $this.find('[id=":' + EntryId + '.fw_title"]').val(QuestionTitle);
                $this.find('[id=":' + EntryId + '.fw_ht"]').val(HelpText);
                $this.find("[id=':" + EntryId + ".fw_select'] option[value='" + typeId + "']").attr("selected", true);
                
                /**如果是必填项，设置为选中状态**/
                Required && $this.find("[id=':" + EntryId + ".fw_req']").attr("checked", true);
                /**通过live添加choice中的delete事件**/
                $('.item_delete_button').live('click', function(){
                    $(this).parent('li').remove();
                });
                $(".item_delete_button_other").live('click', function(){
                    $(this).parent('li').prev('li').find('.add_other_option').css('display', '');
                    $(this).parent('li').remove();
                });
                /**choice添加**/
                switch (EntryType) {
                    case 1:
                        entry = '<input type="text" value="Their answer" class="widget-disabled-preview" disabled="true" name="undefined">';
                        break;
                    case 2:
                        entry = '<input type="text" style="height: 7em; width: 35em;" value="Their longer answer" disabled="true" name="undefined" class="widget-disabled-preview">';
                        break;
                    case 3:
                        entry = $('<ul class="widget-group-ul"></ul>');
                        var is_other;
                        var other_num;
                        var other_li;
                        var add_option = '<li><input type="radio" name="" disabled="true"><input type="text" value="click to add option" class="widget-ghost-input"><span class="sv_inline_block"><label class="add_other_option">or <a href="#">add "Other"</a></label></span></li>';
                        var add_option_o = '<li><input type="radio" name="" disabled="true"><input type="text" value="click to add option" class="widget-ghost-input"><span class="sv_inline_block"><label style="display:none" class="add_other_option">or <a href="#">add "Other"</a></label></span></li>';
                        /**是否有跳转页**/
                        $this.find("[id=':" + EntryId + ".fw_gtpf']").css("display", '');
                        if (is_Goto) {
                            $this.find("[id=':" + EntryId + ".fw_gtpcb']").attr("checked", true);
                        }
                        
                        $.each(Choices, function(index, item){
                            var SelectedByDefault = this.SelectedByDefault ? "checked" : "";
                            var Value = this.Value;
                            var Img = typeof(this.Img_url) == 'undefined' ? "" : this.Img_url;
                            var Label = this.Label;
                            is_other = this.is_other;
                            if (!is_other) {
                                if (is_Goto) {
                                    var GoToQues = parseInt(this.GoToQues);
                                    var selectItem = self.getGtpSelect(EntryId, GoToQues);
                                    $("[id=:" + EntryId + ".fw_gtpf]").checked = false;
                                    var li = '<li><input type="radio" ' + SelectedByDefault + ' name="item_group:' + EntryId + '" value="' + Value + '">' +
                                    '<input type="text" class="" value="' +
                                    Value +
                                    '" style="text-align: left;" dir="ltr">img:http://<input class="img_url" value=' +
                                    Img +
                                    '>or<input type="button" value="上传" class="upload_btn">' +
                                    selectItem +
                                    Survey.item_delete_button +
                                    '</li>';
                                    var li_first = '<li><input type="radio" ' + SelectedByDefault + ' name="item_group:' + EntryId + '" value="' + Value + '">' +
                                    '<input type="text" class="" value="' +
                                    Value +
                                    '" style="text-align: left;" dir="ltr">img:http://<input class="img_url" value=' +
                                    Img +
                                    '>or<input type="button" value="上传" class="upload_btn">' +
                                    selectItem +
                                    '</li>';
                                }
                                else {
                                    $("[id=:" + EntryId + ".fw_gtpf]").checked = false;
                                    var li = '<li><input type="radio" ' + SelectedByDefault + ' name="item_group:' + EntryId + '" value="' + Value + '">' +
                                    '<input type="text" class="" value="' +
                                    Value +
                                    '" style="text-align: left;" dir="ltr">img:http://<input class="img_url" value=' +
                                    Img +
                                    '>or<input type="button" value="上传" class="upload_btn">' +
                                    Survey.item_delete_button +
                                    '</li>';
                                    var li_first = '<li><input type="radio" ' + SelectedByDefault + ' name="item_group:' + EntryId + '" value="' + Value + '">' +
                                    '<input type="text" class="" value="' +
                                    Value +
                                    '" style="text-align: left;" dir="ltr">img:http://<input class="img_url" value=' +
                                    Img +
                                    '>or<input type="button" value="上传" class="upload_btn">' +
                                    '</li>';
                                }
                                entry.append(index == 0 ? li_first : li);
                            }
                            else {
                                other_num = index;
                                other_li = '<li><input type="radio" ' + SelectedByDefault + ' name="item_group:' + EntryId + '" mark="other"> 其他: <input type="text" value="Their own answer" disabled="" class="widget-disabled-preview"><span style="margin: auto 5px; cursor: default;" class="item_delete_button_other">x</span></li>';
                            }
                        });
                        
                        //$this.find("[id=':" + EntryId + ".fw_req']");
                        is_other ? entry.append(add_option_o).append(other_li) : entry.append(add_option);
                        break;
                    case 4:
                        entry = $('<ul class="widget-group-ul"></ul>');
                        var is_other;
                        var other_num;
                        var other_li;
                        var add_option = '<li><input type="checkbox" name="" disabled="true"><input type="text" value="click to add option" class="widget-ghost-input"><span class="sv_inline_block"><label class="add_other_option">or <a href="#">add "Other"</a></label></span></li>';
                        var add_option_o = '<li><input type="checkbox" name="" disabled="true"><input type="text" value="click to add option" class="widget-ghost-input"><span class="sv_inline_block"><label style="display:none" class="add_other_option">or <a href="#">add "Other"</a></label></span></li>';
                        
                        $.each(Choices, function(index, item){
                            var SelectedByDefault = this.SelectedByDefault ? "checked" : "";
                            var Value = this.Value;
                            var Img = typeof(this.Img_url) == 'undefined' ? "" : this.Img_url;
                            var Label = this.Label;
                            var GoToPage = this.GoToPage;
                            is_other = this.is_other;
                            if (!is_other) {
                                var li = '<li><input type="checkbox" ' + SelectedByDefault + ' name="item_group:' + EntryId + '" value="' + Value + '">' +
                                '<input type="text" class="" value="' +
                                Value +
                                '" style="text-align: left;" dir="ltr">img:http://<input class="img_url" value=' +
                                Img +
                                '>or<input type="button" value="上传" class="upload_btn">' +
                                Survey.item_delete_button +
                                '</li>';
                                var li_first = '<li><input type="checkbox" ' + SelectedByDefault + ' name="item_group:' + EntryId + '" value="' + Value + '">' +
                                '<input type="text" class="" value="' +
                                Value +
                                '" style="text-align: left;" dir="ltr">img:http://<input class="img_url" value=' +
                                Img +
                                '>or<input type="button" value="上传" class="upload_btn">' +
                                '</li>';
                                entry.append(index == 0 ? li_first : li);
                            }
                            else {
                                other_num = index;
                                other_li = '<li><input type="checkbox" ' + SelectedByDefault + ' name="item_group:' + EntryId + '" mark="other"> 其他: <input type="text" value="Their own answer" disabled="" class="widget-disabled-preview"><span style="margin: auto 5px; cursor: default;" class="item_delete_button_other">x</span></li>';
                            }
                        });
                        is_other ? entry.append(add_option_o).append(other_li) : entry.append(add_option);
                        break;
                    case 5:
                        entry = $('<ol class="widget-group-ol"></ol>');
                        entry_other = '<li><input type="text" mark="select" class="widget-ghost-input" value="click to add option"></li>';
                        $.each(Choices, function(index, item){
                            var SelectedByDefault = this.SelectedByDefault ? "checked" : "";
                            var Value = this.Value;
                            var Label = this.Label;
                            var GoToPage = this.GoToPage;
                            var is_other = this.is_other;
                            
                            var option = '<li><input type="text" class="" value="' + Value + '" style="text-align: left;" dir="ltr"><span style="margin: auto 5px; cursor: default;" class="item_delete_button">x</span></li>';
                            var option_first = '<li><input type="text" class="" value="' + Value + '" style="text-align: left;" dir="ltr"></li>';
                            entry.append(index == 0 ? option_first : option);
                        });
                        entry.append(entry_other);
                        break;
                    default:
                        
                }
                $this.find(".widget-preview").html(entry).data("entryObject", this);
                return $this;
            }, EntryId);
            
        });
    },
    convertToEntry: function(){
        var self = this;
        $("[id*=fw_done]").live('click', function(e){
            var $id = $(this).attr('id');
            var id_num = parseInt($id.substring(1, $id.indexOf('.')));
            var form_entry = $(Survey.form_widget_entry(id_num));
            var container = $(this).parents('.form-widget-container');
            var qtId = parseInt(self.getQtId(id_num));
            var is_require = self.is_require(id_num);
            var $position = $(".form-widget-container").index($(this).parents(".form-widget-div").parents(".form-widget-container")) + 1;
            var title = $(Survey.q_title).html('<span name="title">' + self.getEntryTitle(id_num) + '</span>').append("<font class=':" + id_num + ".fw_qno' color='#67A7E3'>(第" + $position + "题)</font>");
            var help = $(Survey.q_help).html(self.getEntryDes(id_num));
            var entry = "";
            var ids = self.getEntryIds().toString();
            is_require && title.append(Survey.q_require);
            switch (qtId) {
                case 1:
                    entry = self.parseText(id_num);
                    break;
                case 2:
                    entry = self.parseTextarea(id_num);
                    
                    break;
                case 3:
                    entry = self.parseRadio(id_num);
                    
                    break;
                case 4:
                    entry = self.parseCheckbox(id_num);
                    break;
                case 5:
                    entry = self.parseSelect(id_num);
                    
                    break;
                default:
                    
            }
            container.find(".form-widget-entry").remove();
            form_entry.append(title).append(help).append(entry);
            form_entry.attr({
                'entryType': qtId
            });
            container.append(form_entry);
            if (ids.indexOf(id_num) != -1) {
                self.changeEntry(form_entry);
            }
            else {
                self.addEntry(form_entry);
            }
            
            container.unbind_();
            container.drag({
                dragHandle: ".form-widget-entry",
                dragEnd: function($this){
                    return function(){
                        on_drag_end.call(this, function(){
                            $this.rePosition();
                            $("[id*=fw_gtpcb]:checked").each(function(){
                                var $id = $(this).attr('id');
                                var id_num = parseInt($id.substring(1, $id.indexOf('.')));
                                $("[class=:" + id_num + ".fw_gp]").each(function(){
                                    var val_ = $(this).val();
                                    $(this).replaceWith($this.getGtpSelect(id_num, val_))
                                });
                                
                            });
                            self.setQuestionNum();
                        });
                    };
                }(self),
                draging: on_drag,
                dragStart: on_drag_start
            });
            container.find(".form-widget-div").css('display', 'none');
        });
    },
    setQuestionNum: function(){
        $("[class$=fw_qno]").each(function(){
            var po = $(this).parents(".form-widget-container");
            var index = $(".form-widget-container").index(po) + 1;
            $(this).html("(第" + index + "题)");
        });
    },
    getEntryTitle: function(num){
        return $("[id=':" + num + ".fw_title']").val();
    },
    getEntryDes: function(num){
        return $("[id=':" + num + ".fw_ht']").val();
    },
    parseText: function(num){
        var ht_text = '<input type="text" disabled="true" name="' + num + '.entry.single" class="q-short">';
        return ht_text;
    },
    parseTextarea: function(num){
        var ht_text = '<textarea disabled="true" name="' + num + '.entry.single" class="q-long" cols="60" rows="5"></textarea>';
        return ht_text;
    },
    parseSelect: function(num){
        var select_ = $('<select name="' + num + '.entry.single"></select>');
        var lists = $("[id=:" + num + Survey.setting.widget.widget_div.preview.id_end + "]").find(".widget-group-ol :text:not('.widget-ghost-input')");
        lists.each(function(){
            var value = $(this).val();
            var option = '<option  value="' + value + '">' + value + '</option>';
            select_.append(option);
        });
        return select_;
    },
    parseCheckbox: function(num){
        var ht_ul = $('<ul class="widget-group-ul"></ul>');
        var checkboxes = $("[id=:" + num + Survey.setting.widget.widget_div.preview.id_end + "]").find(":checkbox[name='item_group:" + num + "']");
        checkboxes.each(function(){
            var checked = $(this).is(':checked') ? 'checked' : '';
            var value = $(this).next(":text").val().replace(/[><]/gi, "");
            var is_other = $(this).attr('mark') == "other";
            if (!is_other) 
                var img = $(this).nextAll(".img_url").val().replace(/[><]/gi, "");
            var li = '<li class="ss-choice-item"><input img_url="' + img + '" type="checkbox"  ' + checked + ' name="' + num + '.entry.group" value="' + value + '">' +
            '<label for="' +
            num +
            '.entry.group">' +
            value +
            '</label><img align=absmiddle src=http://' +
            img +
            '></li>';
            var other_li = '<li><input type="checkbox" ' + checked + ' mark="other" name="' + num + '.entry.group"> 其他: ' +
            '<input type="text" maxlength=50 value="">' +
            '</li>';
            ht_ul.append(is_other ? other_li : li);
        });
        return ht_ul;
    },
    parseRadio: function(num){
        var ht_ul = $('<ul class="widget-group-ul"></ul>');
        var radios = $("[id=:" + num + Survey.setting.widget.widget_div.preview.id_end + "]").find(":radio[name='item_group:" + num + "']");
        radios.each(function(){
            var gotoques = $(this).siblings("select[class$=fw_gp]").eq(0).val();
            var checked = $(this).is(':checked') ? 'checked' : '';
            var value = $(this).next(":text").val().replace(/[><]/gi, "");
            var is_other = $(this).attr('mark') == "other";
            if (!is_other) 
                var img = $(this).nextAll(".img_url").val().replace(/[><]/gi, "");
            var li = '<li class="ss-choice-item"><input img_url="' + img + '" Gtp="' + gotoques + '" type="radio" ' + checked + ' name="http://' + num + '.entry.group" value="' + value + '">' +
            '<label for="' +
            num +
            '.entry.group">' +
            value +
            '</label><img align=absmiddle src=http://' +
            img +
            '></li>';
            var other_li = '<li><input type="radio" ' + checked + ' mark="other" name="' + num + '.entry.group"> 其他: ' +
            '<input type="text" maxlength=50 value="">' +
            '</li>';
            ht_ul.append(is_other ? other_li : li);
        });
        return ht_ul;
    },
    is_require: function(num){
        return $("[id*=:" + num + ".fw_req]").is(":checked");
    },
    getFormTitle: function(){
        return $(Survey.form_title).val();
    },
    getFormDescription: function(){
        return $(Survey.form_description).val();
    },
    getQtId: function(num){
        var select = $("select[id=':" + num + ".fw_select']");
        return select.val();
    },
    clone: function(){
        var tool_var = Survey.setting.widget.tool_bar;
        var self = this;
        
        $(tool_var.clone).live('click', function(e){
            $('.form-widget-div:visible').find("[id*=.fw_done]").trigger('click');
            self.addFormWidget();
            return false;
        });
    },
    uploadEvent: function(){
        var $upload_file = $("#upload_file");
        $upload_file.val("");
        $(".upload_btn").live("click", function(){
            $upload_file.trigger("click");
            return false;
        });
        $upload_file.change(function(){
            $("#addbanner").ajaxSubmit({
                data: {
                    b_purpose: $radio.attr("title")
                },
                success: function(data){
                    $("#savebanner").html(data);
                    $("#upload_status .busying").fadeOut(400);
                }
            });
        });
    },
    remove: function(){
        var tool_var = Survey.setting.widget.tool_bar;
        var self = this;
        $(tool_var.remove).live('click', function(e){
            e.stopPropagation();
            var entryIds = self.getEntryIds();
            if (confirm("你想删除该项吗?")) {
                $(this).parents('.form-widget-container').fadeOut(400, function(){
                    var entryId = $(this).find(".form-widget-entry").attr('entryid');
                    for (var i = 0; i < entryIds.length; i++) {
                        if (entryId == entryIds[i]) {
                            self.addRemoveOption(entryId);
                        }
                    }
                    $(this).remove();
                    self.delEntryById(entryId);
                    if ($('.form-widget-container').length == 0) {
                        self.addFormWidget();
                    }
                    self.setQuestionNum();
                });
            }
            return false;
        });
    },
    getEntryIds: function(){
        var $ids = [];
        $.each(this.options.Entries, function(index, item){
            $ids.push(item.EntryId);
        });
        return $ids;
    },
    editEntry: function(element){
        var tool_var = Survey.setting.widget.tool_bar;
        var self = this;
        $(tool_var.edit).live('click', function(){
            var container = $(this).parents('.form-widget-container');
            container.find(".form-widget-entry").remove();
            container.siblings('.form-widget-container').find('.form-widget-div:visible').each(function(){
                $("[id*=.fw_done]", this).trigger('click');
            });
            container.find(".form-widget-div").css('display', '');
            return false;
        });
    },
    addFormWidget: function(func, num, drag){
        //获取widget_div——是form_widget的表单编辑部分
        var widget_div = Survey.get_widget_div(num);
        if (func) {
            widget_div = func($(widget_div));
        }
        //获取form_widget
        var $form_widget = $(Survey.setting.form_widget);
        $form_widget.append(widget_div).css('display', 'none').appendTo(Survey.widget_container).fadeIn(500);
        $(".form-widget-container").hover(function(){
            $(this).find('.form-widget-entry').css({
                'background': '#FFF9DD'
            });
            $(this).find(".tool-bar").css("visibility", 'visible');
        }, function(){
            $(this).find('.form-widget-entry').css({
                'background': '#FFFFFF'
            });
            $(this).find(".tool-bar").css("visibility", 'hidden');
        });
        if (drag) {
            drag();
        }
    },
    addOption: function(){
        var self = this;
        $(".widget-ghost-input").live('click', function(){
            var parent_ul = $(this).parents('ul,ol');
            var pre_li = parent_ul.find('li:first');
            var pre_li_c = pre_li.clone().append(Survey.item_delete_button);
            pre_li_c.find(":text[dir=ltr]").val("option");
            $('.item_delete_button').live('click', function(){
                $(this).parent('li').remove();
            });
            $(this).parent('li').before(pre_li_c);
        });
    },
    addOtherOption: function(){
        $(".add_other_option").live('click', function(e){
            var id = $(this).parents('.widget-preview').attr('id');
            var id_num = id.substring(1, id.indexOf('.'));
            var is_check = $(this).parents('li').find(":checkbox").length > 0;
            is_check ? $(this).parents('li').after(Survey.other_option_check(id_num)) : $(this).parents('li').after(Survey.other_option_radio(id_num));
            $(this).css('display', 'none');
            $(".item_delete_button_other").live('click', function(){
                $(this).parent('li').prev('li').find('.add_other_option').css('display', '');
                $(this).parent('li').remove();
            });
            return false;
        });
    },
    changeForm: function(){
        var height = $("#body_container")[0].scrollHeight
        var width = $("#body_container").width();
        var qNum = $(this.getFormWidgetContainer()).length;
        var formId = this.options.FormId;
        this.setFormQesNum(qNum);
        this.setFormHeight(height);
        this.setFormWidth(width);
    },
    changeEntry: function(entry){
        var self = this;
        var optionsList = this.getEntryIds().toString();
        var EntryId, QuestionTitle, HelpText, EntryType, Position, Required, OtherOptionEnabled, choices, is_otherSelected, isGoto;
        EntryId = parseInt(entry.attr('entryId'));
        QuestionTitle = entry.find('.q_title [name="title"]').html();
        HelpText = entry.find('.q_help').html();
        EntryType = parseInt(entry.attr('entrytype'));
        Position = $(".form-widget-container").index(entry.parents('.form-widget-container'));
        Required = entry.find('.q_require').length > 0;
        choices = self.createChoice(entry);
        isGoto = $("[id=:" + EntryId + ".fw_gtpcb]").attr('checked');
        
        var entry_by = self.getEntryById(EntryId);
        entry_by.QuestionTitle = QuestionTitle.replace(/\s/, '');
        entry_by.HelpText = HelpText.replace(/\s/, '');
        entry_by.EntryType = EntryType;
        entry_by.Choices = choices;
        entry_by.Required = Required;
        entry_by.Position = Position;
        entry_by.is_Goto = isGoto;
    },
    createChoice: function(entry){
        var choices = [];
        var items = entry.find(':radio,:checkbox,select>option');
        items.each(function(){
            var $gotoques = parseInt($(this).attr("gtp")) ? parseInt($(this).attr("gtp")) : -2;
            var is_check = $(this).is(":checked");
            var val = $(this).val().replace(/\s/, '');
            var img = $(this).attr("img_url");
            var is_other = $(this).attr("mark") == "other";
            if (is_other) 
                val = "其他";
            var item = {
                SelectedByDefault: is_check,
                Value: val,
                Img_url: img,
                Label: "",
                GoToQues: $gotoques,
                is_other: is_other
            };
            choices.push(item);
        });
        
        return choices;
    },
    getFormWidgetContainer: function(){
        var containers = [];
        $(".form-widget-container").each(function(){
            if ($(this).has('.form-widget-entry').length > 0) {
                containers.push(this);
            }
        });
        return containers;
    },
    rePosition: function(){
        var self = this;
        for (var i = 0; i < self.options.Entries.length; i++) {
            var entryId = self.options.Entries[i].EntryId;
            $position = $(".form-widget-container").index($(".form-widget-entry[entryid='" + entryId + "']").parents(".form-widget-container"));
            self.options.Entries[i].Position = parseInt($position);
        }
    },
    clearInfo: function(){
        var entries = this.options.Entries;
        for (var i = 0; i < entries.length; i++) {
            entries[i].is_new = 0;
        }
        this.options.removeOption = [];
    },
    save_all: function(url){
    
        var url = url != "" && url || "/admin/admin_form/saveform";
        var self = this;
        
        $("#save_all").bind('click', function(e, not_show){
            self.changeForm();
            var form_ = JSON.stringify(self.options);
            var formKey = self.options.FormKey;
            if (typeof form_ != "undefined") {
                $.ajax({
                    url: url,
                    data: {
                        'data': form_,
                        'formKey': formKey
                    },
                    type: 'POST',
                    success: function(data){
                        if (data == "1") {
                            if (!not_show) {
                                $.facebox("<h2>save success</h2>");
                                setTimeout(function(){
                                    $(document).trigger('close.facebox')
                                }, 1000);
                            }
                            self.clearInfo();
                        }
                        else {
                            if (!not_show) {
                                $.facebox("<h2>save failed</h2>");
                                setTimeout(function(){
                                    $(document).trigger('close.facebox')
                                }, 1000);
                            }
                        }
                    },
                    error: function(){
                    
                    }
                });
            }
        });
        
        //        setInterval(function(){
        //            $("#save_all").trigger('click', true);
        //        }, 600000);
    },
    getFormId: function(){
        return this.options.FormId;
    },
    setFormQesNum: function(num){
        this.options.FormQesNum = num;
    },
    getFormQesNum: function(){
        return this.options.FormQesNum;
    },
    setFormHeight: function(height){
        this.options.FormHeight = height;
    },
    getFormHeight: function(){
        return this.options.FormHeight;
    },
    setFormWidth: function(width){
        this.options.FormWidth = width;
    },
    getFormWidth: function(){
        return this.options.FormWidth;
    },
    setFormTitle: function(title){
        this.options.FormTitle = title;
    },
    getFormTitle: function(){
        return this.options.FormTitle;
    },
    setFormDes: function(des){
        this.options.FormDescription = des;
    },
    getFormDes: function(){
        return this.options.FormDescription;
    },
    getRemoveOption: function(){
        return this.options.removeOption;
    },
    addRemoveOption: function(id){
        if (!this.options.removeOption) {
            this.options.removeOption = [];
        }
        this.options.removeOption.push(parseInt(id));
    },
    delEntryById: function(id){
        var Entries = this.options.Entries;
        for (var i = 0; i < Entries.length; i++) {
            if (Entries[i].EntryId == id) {
                Entries.splice(i, 1);
            }
        }
    },
    getEntryById: function(id){
        var Entries = this.options.Entries;
        for (var i = 0; i < Entries.length; i++) {
            if (Entries[i].EntryId == id) {
                return Entries[i];
            }
        }
        return false;
    },
    addEntry: function(entry){
        var self = this;
        var optionsList = this.getEntryIds().toString();
        var EntryId, QuestionTitle, HelpText, EntryType, Position, Required, OtherOptionEnabled, choices, is_otherSelected, is_new;
        EntryId = parseInt(entry.attr('entryId'));
        QuestionTitle = entry.find('.q_title [name="title"]').html();
        HelpText = entry.find('.q_help').html();
        EntryType = parseInt(entry.attr('entrytype'));
        Position = $(".form-widget-container").index(entry.parents('.form-widget-container'));
        Required = entry.find('.q_require').length > 0;
        choices = self.createChoice(entry);
        
        if (optionsList == "") {
            is_new = 1;
        }
        else {
            is_new = optionsList.indexOf(EntryId) < 0 ? 1 : 0;
        }
        var entry_ = {
            EntryId: EntryId,
            QuestionTitle: QuestionTitle,
            HelpText: HelpText,
            EntryType: EntryType,
            Choices: choices,
            Required: Required,
            Position: Position,
            is_new: is_new
        };
        this.options.Entries.push(entry_);
    },
    getEntries: function(){
        return this.options.Entries;
    }
});

(function($){
    $.fn.drag = function(option){
        var defaultOption = {
            dragHandle: ".handle",
            dragStart: $.noop,
            draging: $.noop,
            dragEnd: $.noop
        };
        
        var option = $.extend(defaultOption, option || {});
        var self = this;
        this.option = option;
        
        $(this).each(function(item){
            if (isNaN(parseInt($(this).css('left')))) {
                $(this).css('left', "0px");
            }
            if (isNaN(parseInt($(this).css('top')))) {
                $(this).css('top', "0px");
            }
            
            $(this).bind('dragStart', option.dragStart);
            $(this).bind('dragEnd', option.dragEnd);
            $(this).bind('draging', option.draging);
            
            var handle = $(this).find(self.option.dragHandle).length > 0 ? $(this).find(self.option.dragHandle) : $(this);
            handle.data("dragObject", this)
            handle.mousedown(function(event){
                event = fix(event);
                if (event.which != 1) {
                    return true;
                }
                var dragObj = $($(this).data("dragObject"));
                dragObj.trigger("dragStart");
                dragObj.data('lastMouseX', event.clientX);
                dragObj.data('lastMouseY', event.clientY);
                $(document).mouseup((function(that){
                    return function(){
                        end.apply(that, arguments);
                    };
                })(this));
                $(document).mousemove((function(that){
                    return function(){
                        drag.apply(that, arguments);
                    };
                })(this));
                return false;
            });
        });
        var drag = function(event){
            event = fix(event);
            if (event.which == 0) {
                return end();
            }
            var _clientX = event.clientX;
            var _clientY = event.clientY;
            var dragObj = $($(this).data("dragObject"));
            if (dragObj.data('lastMouseX') == _clientY && dragObj.data('lastMouseyY') == _clientX) {
                return false;
            }
            var _lastY = parseInt(dragObj.css('top'));
            var _lastX = parseInt(dragObj.css('left'));
            
            var newX, newY;
            newX = _lastX + _clientX - dragObj.data('lastMouseX');
            newY = _lastY + _clientY - dragObj.data('lastMouseY');
            
            dragObj.css('left', newX + "px");
            dragObj.css('top', newY + "px");
            dragObj.data('lastMouseX', _clientX);
            dragObj.data('lastMouseY', _clientY);
            dragObj.trigger("draging", event);
            return false;
        };
        var end = function(event){
            event = fix(event);
            var dragObj = $($(this).data("dragObject"));
            dragObj.trigger("dragEnd");
            return false;
        };
        var fix = function(event){
            event = event || window.event;
            event.x = event.x || event.pageX;
            event.y = event.y || event.pageY;
            event.which = event.which || event.button;
            event.srcElement = event.srcElement || event.target;
            event.keyCode = event.keyCode || event.charCode;
            return event;
        }
    }
})(jQuery)

function on_drag_start(e, x, y){
    var top = $(this).offset().top;
    var left = $(this).offset().left;
    var scrollHeight_ = $("#body_container")[0].scrollHeight;
    var clientHeight_ = $("#body_container")[0].clientHeight;
    $(this).css('position', 'absolute');
    $(this).css('left', left + 'px');
    $(this).css('top', top + 'px');
    $(this).width(scrollHeight_ - clientHeight_ > 0 ? "633px" : "650px");
    $(this).css({
        'opacity': '0.5',
        'z-index': '200'
    });
    $(this).before('<div class="ghost"></div>');
    $(".ghost").height($(e.target).innerHeight());
    onselectstart = "return false"
}

function on_drag(event, ev){
    var mouse_x = ev.x;
    var mouse_y = ev.y
    $this = this;
    $('#widget-container > div').each(function(index, element){
        if (element != $this && $(element).attr('className') != 'ghost') {
            var left = $(element).offset().left;
            var right = $(element).offset().left + $(element).width();
            var top = $(element).offset().top;
            var bottom = $(element).offset().top + $(element).height();
            
            if (mouse_x >= left && mouse_x <= right && mouse_y >= top && mouse_y <= bottom) {
                var ghost_left = $('.ghost').offset().left || 0;
                var ghost_top = $('.ghost').offset().top || 0;
                
                $('.ghost').remove();
                
                if (ghost_left >= left && ghost_top >= top) 
                    $(element).before('<div class="ghost"></div>');
                else 
                    if (ghost_left < left && ghost_top > top) 
                        $(element).before('<div class="ghost"></div>');
                    else 
                        $(element).after('<div class="ghost"></div>');
                $(".ghost").height($(event.target).height());
                
                return;
            }
        }
    });
}

function on_drag_end(func){
    var left = $('.ghost').offset().left - 5;
    var top = $('.ghost').offset().top - 5;
    var element = $(this);
    element.animate({
        'left': left,
        'top': top,
        'opacity': '1'
    }, 100, function(){
        element.css({
            'position': 'static',
            'z-index': '0'
        });
        $(document).unbind('mousemove');
        $(document).unbind('mouseup');
        $('.ghost').replaceWith(element);
        if (func) {
            func();
        }
    });
}
